package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.common.MessageConst;
import com.itheima.entity.Result;
import com.itheima.service.GenderService;
import com.itheima.service.ReportService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @Author : wangjie
* @CreateDate : 2020/4/11 10:35
* @Version : 1.0
* @Description : 图表前端控制器
*/
@RestController
@RequestMapping("report")
@Slf4j
public class ReportController {

    //依赖注入
    @Reference
    private ReportService reportService;

    @Reference
    GenderService genderService;

    /*
     * 性别统计
     * */
    @RequestMapping("/getGenderReport")
    public Result getGenderReport(){
        try {
            List<Object> sexList = new ArrayList<>();
            //调 service
            List<Map<String,Object>> zongsex = genderService.getGenderReport();


            for (Map<String, Object> map : zongsex) {
                String sex = (String) map.get("name");

                if (sex != null) {
                    if (sex.equals("1")) {
                        sex = "女";
                    } else if (sex.equals("2")) {
                        sex = "男";
                    } else {
                        sex = "未填写性别";
                    }
                    sexList.add(sex);
                }
            }
            System.out.println("+++++++++++++++++++++++");
            System.out.println("sexLise = " + sexList);

            for (Map<String, Object> map : zongsex) {
                String name = (String) map.get("name");
                if (name != null) {
                    if (name.equals("1")) {
                        name = "女";
                        map.put("name", name);
                    } else if (name.equals("2")) {
                        name = "男";
                        map.put("name", name);
                    } else {
                        name = "未填写性别";
                        map.put("name", name);
                    }
                    System.out.println("+++++++++++++");
                    System.out.println("name = " + name);
                }
            }

            Map<String,Object> resultMap = new HashMap<>();
            resultMap.put("sexLise",sexList);
            resultMap.put("zongsex",zongsex);

            return new Result(true, MessageConst.GET_MEMBER_GENDER_REPORT_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_GENDER_REPORT_FAIL);
        }
    }



    /**
     * 会员数量统计
     * @return
     */
    @RequestMapping("getMemberReport")
    public Result getMemberReport(){
        try {
            //构建月份列表
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MONTH,-12);//月份向前退12
            List<String> months=new ArrayList<>();//创建集合存储月份信息
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy.MM");//日期格式化
            for (int i = 0; i <12 ; i++) {
                calendar.add(Calendar.MONTH,1);//当期日期向后加一个月,即为12个月的开始月份
                Date date = calendar.getTime();//获取当前日期
                //将格式化日期(月份存入集合中)
                months.add(sdf.format(date));
            }
            //调用service方法 得到每月会员数据
            List<Integer> monthCount =reportService.findCountByMonths(months);
            Map<String,Object> map=new HashMap<>();//创建map集合存储月份集合和每月会员数据
            map.put("months",months);
            map.put("memberCount",monthCount);
            //返回图表数据
            return new Result(true,MessageConst.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_MEMBER_NUMBER_REPORT_FAIL);
        }
    }

    /**
     * 获取套餐预约占比
     * @return
     */
    @RequestMapping("getSetmealReport")
    public Result getSetmealReport(){

        try {
            //获取各套餐的占比数据,调用service方法
            List<Map> setmealList = reportService.findSetmealCount();
            List<String> setmealNames=new ArrayList<>();//存储套餐名字集合
            for (Map map : setmealList) {
                //遍历集合获取套餐名字
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            Map<String,Object> map=new HashMap();
            map.put("setmealNames",setmealNames);
            map.put("setmealCount",setmealList);
            //向客户端响应
            return new Result(true,MessageConst.ACTION_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.ACTION_FAIL);
        }
    }

    /**
     * 获取运营数据
     * @return
     */
    @RequestMapping("getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            //调用service, 获取运营数据
            Map map = reportService.getBusinessReportData();
            //返回报表数据
            return new Result(true, MessageConst.ACTION_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }

    /**

     *导出运营数据报表
     *@return
     */
    @RequestMapping("exportBusinessReport")
    public Result exportBusinessReport(HttpServletResponse response){
        try {
            //调用Service方法获取统计数据
            Map map = reportService.getBusinessReportData();
            //获得当前日期
            String reportDate = (String) map.get("reportDate");
            //获取会员有关数据
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            //获取与预约有关数据
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            //获得热门套餐数据
            List<Map<String, Object>> hotSetmeal = (List<Map<String, Object>>) map.get("hotSetmeal");
            //利用POIUtils工具类将数据写入到Excel
            InputStream inputStream = ReportController.class.getClassLoader().getResourceAsStream("report_template.xlsx");
            //创建Workbook对象，获取工作表
            Workbook workbook = new XSSFWorkbook(inputStream);
            Sheet sheet = workbook.getSheetAt(0);
            //获取报表日期行
            Row row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);
            //获取新增会员及会员总数行
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember);
            row.getCell(7).setCellValue(totalMember);
            //获取本周新增会员及本月新增会员行
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);
            row.getCell(7).setCellValue(thisMonthNewMember);
            //获取今日预约及到诊数行
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);
            row.getCell(7).setCellValue(todayVisitsNumber);
            //获取本周预约及到诊数行
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);
            row.getCell(7).setCellValue(thisWeekVisitsNumber);
            //获取本月预约及到诊
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);
            row.getCell(7).setCellValue(thisMonthVisitsNumber);
            //获取热门套餐行，动态写入数据
            int rownum = 12;
            for (Map<String, Object> setmealMap : hotSetmeal) {
                //获取当前套餐中的信息
                String name = (String) setmealMap.get("name");
                Long setmeal_count = (Long) setmealMap.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) setmealMap.get("proportion");
                String remark = (String) setmealMap.get("remark");

                row = sheet.getRow(rownum);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
                row.getCell(7).setCellValue(remark);
                rownum++;
            }
            //通过输出流进行文件下载
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename="+reportDate+"_report.xlsx");
            workbook.write(out);
            out.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ACTION_FAIL);
        }
    }
}
